class Solution {
    public int totalFruit(int[] fruits) {
        int n=fruits.length;
        int left=0,right=0,kinds=0,ret=0;
        int[] hash = new int[n];
        while(right<n){
            if (hash[fruits[right]]==0)
                kinds++;
            hash[fruits[right]]++;
            while(kinds>2){
                if(hash[fruits[left]]==1)
                    kinds--;
                hash[fruits[left++]]--;
            }
            ret=Math.max(ret,right-left+1);
            right++;
        }
        return ret;
    }
}